<template>
  <div class="settle-account-container">
    <div class="top-tab">
      <a-tabs v-model:active-key="curPage" @change="tabChange" size="mini">
        <a-tab-pane v-for="item in tabList" :key="item.key">
          <template #title>
            <span>{{ item.label }}</span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="table-bottom table-gl-w">
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :max-num="5" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getList">
          <template #headerLeft>
            <a-space v-if="curPage == '1'">
              <a-button class="gray-outline" @click="batchSettle">批量确认结算</a-button>
              <a-button class="gray-outline">结算规则设置</a-button>
            </a-space>
          </template>
          <template #tableBody>
            <a-table size="mini" :bordered="{ headerCell: true, wrapper: true }" v-model:selected-keys="ids" row-key="id" :row-selection="{ type: 'checkbox', showCheckedAll: true, width: 40, onlyCurrent: false }" class="table-two-line" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column title="序号" #cell="{ rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
                <a-table-column title="任务ID" #cell="{ record }" :width="160">{{ record.code }}</a-table-column>
                <a-table-column title="产品">
                  <a-table-column title="图片" #cell="{ record }" :width="60">
                    <ImgPopover :src="imgUrl(record)">
                      <template #con>
                        <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                      </template>
                    </ImgPopover>
                  </a-table-column>
                  <a-table-column title="SKU" #cell="{ record }" :width="80">
                    <TextLimit position="top" :rows="1" :val="$extract(record, 'product.sku') || '--'" />
                  </a-table-column>
                </a-table-column>
                <a-table-column title="子任务" #cell="{ record }" :width="120">字段未对接</a-table-column>
                <a-table-column title="任务执行人" #cell="{ record }" :width="110">
                  <div class="task_user" style="width: 100%; height: 100%">
                    <a-space>
                      <a-popover>
                        <div class="text-limit" style="width: 100px">{{ getExecuterUser(record) || '--' }}</div>
                        <template #content>
                          <div style="max-width: 300px">
                            {{ getExecuterUser(record) || '--' }}
                          </div>
                        </template>
                      </a-popover>
                    </a-space>
                  </div>
                </a-table-column>
                <a-table-column title="执行部门" #cell="{ record }" :width="100">{{ $extract(record, 'employer.deptName') }}</a-table-column>
                <a-table-column title="结算金额" #cell="{ record }" :sortable="sortable" data-index="amount" :width="100">字段未对接</a-table-column>
                <a-table-column title="主任务结算金额" #cell="{ record }" :sortable="sortable" data-index="allAmount" :width="130">字段未对接</a-table-column>
                <a-table-column title="结算规则ID" #cell="{ record }" :width="100">字段未对接</a-table-column>
                <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column>
                <a-table-column title="服务内容" #cell="{ record }" :width="80">
                  <TextLimit :val="$extract(record, 'taskRequire.serContent')" :rows="1" position="top" />
                </a-table-column>
                <a-table-column title="主任务总费用" #cell="{ record }" :sortable="sortable" data-index="allAmount" :width="120">字段未对接</a-table-column>
                <a-table-column title="甲方" #cell="{ record }" :width="80">字段未对接</a-table-column>
                <a-table-column title="完成时间" #cell="{ record }" :sortable="sortable" data-index="gmtFinish" :width="130">
                  {{ $setTime(record.gmtFinish, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column title="接单时间" #cell="{ record }" :sortable="sortable" data-index="gmtTake" :width="130">
                  {{ $setTime(record.gmtTake, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column title="任务执行周期" #cell="{ record }" :sortable="sortable" data-index="allAmount" :width="130">字段未对接</a-table-column>
                <a-table-column title="操作" #cell="{ record }" :width="60" align="center" fixed="right" v-if="curPage == '1'">
                  <a-button type="text" @click="showModal(record)">编辑</a-button>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
  </div>
  <a-modal v-model:visible="setSettleModal" title-align="start" title="设置结算金额" :width="500">
    <div class="mb10">
      <span>总任务费用:</span>
      <span style="color: red">¥200</span>
    </div>

    <div class="mb10">
      <a-space>
        <div class="label">渲染渲染(陈伟莹):</div>
        <a-input :style="{ width: '320px' }" placeholder="请输入" allow-clear>
          <template #prefix>￥</template>
        </a-input>
      </a-space>
    </div>
    <div class="mb10">
      <a-space>
        <div class="label">渲染(陈伟莹):</div>
        <a-input :style="{ width: '320px' }" placeholder="请输入" allow-clear>
          <template #prefix>￥</template>
        </a-input>
      </a-space>
    </div>

    <template #footer>
      <a-space>
        <a-button size="small" class="gray-outline" @click="setSettleModal = false">取消</a-button>
        <a-button size="small" type="primary">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { findTaskPage, delTask, revokeTask, countTaskStatus, statTaskFromLocation } from '@/api/task'
  import { Message, Modal, TableSortable } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import useUserStore from '@/store/modules/user'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import _ from 'lodash-es'

  const sortable: TableSortable = { sortDirections: ['ascend', 'descend'], sorter: true }

  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }

  const curPage = ref('1')
  const tabList = ref([
    { label: '待结算', key: '1' },
    { label: '已结算', key: '2' },
  ])
  const searchValue: any = ref({})
  const info: any = ref({})
  const tableList = ref([])
  const ids = ref<Array<string>>([])
  const loading = ref(false)
  const setSettleModal = ref(false)
  const pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  const userInfo = useUserStore()
  const filterItem: any = ref([
    {
      type: 'input_keyword',
      key: 'codeList',
      keyItems: [
        { label: '任务ID', value: 'codeList' },
        { label: '服务内容', value: 'serContentList' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 180,
      isMultiple: true,
    },
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_search',
      key: 'employerName',
      keyWidth: '100',
      value: ref(),
      placeholder: '甲方',
      width: 160,
    },

    {
      key: 'taskType',
      label: '执行部门',
      value: ref(),
      type: 'select',
      width: 110,
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      key: 'taskType',
      label: '执行人',
      value: ref(),
      type: 'select_multiple',
      width: 110,
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },

    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: '100%',
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报设计', value: 'POSTER_SHOP_DESIGN' },
        { label: '换钻调色', value: 'CHANGE_DIAMOND_COLOR' },
        { label: '手绘设计', value: 'HAND_DRAWN_DESIGN' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      type: 'keyword_date_range_custom',
      key: 'gmtFinish',
      keyItems: [{ label: '完成时间', value: 'gmtFinish' }],
      keyWidth: '130',
      label: '完成时间',
      value: ref(),
      width: 240,
    },
  ])

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)
    getList()
  }
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }

  const getList = async () => {
    const params = {
      ...searchValue.value,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    loading.value = true
    const res: any = await findTaskPage(params)
    if (res) {
      tableList.value = res?.data?.records
      pageNation.value.total = res?.data?.total
    }
    loading.value = false
  }

  const tabChange = () => {
    pageNation.value.pageNum = 1
    getList()
  }

  const getUSerList = async () => {
    const params = {
      depart: false,
      needRole: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    if (res) {
      const arr = res.data.records || []
      filterItem.value[4].optionItems = arr.map((e: any) => {
        e.label = e.userName
        e.value = e.id
        return e
      })
    }
  }

  const imgUrl = (data: any) => {
    const arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  const getExecuterUser = (arr: any) => {
    const newArr = arr?.executerList || []
    return newArr.map((item: any) => item.name).join(',')
  }

  const batchSettle = async () => {
    if (!ids.value[0]) return Message.error('请选择要结算的任务')
    Modal.info({
      title: '是否确认结算',
      content: '请再次确认是否确认结算',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        // const params = {
        //   idList: ids.value,
        // }
        // const res: any = await cancelTakeTask(params)
        // if (res) {
        //   Message.success('取消接单成功')
        //   ids.value = []
        //   getList()
        // }
      },
    })
  }

  const showModal = (data: any) => {
    info.value = data
    setSettleModal.value = true
  }

  onMounted(() => {
    getList()
    getUSerList()
  })
</script>

<style lang="less" scoped>
  .settle-account-container {
    // height: calc(100vh - @menuHeight);
    .top-tab {
      background-color: white;
    }
    .table-bottom {
      height: calc(100vh - @menuAndTabHeight);
    }
  }

  .label {
    display: inline-block;
    width: 120px;
    text-align: right;
  }
</style>
